<template>
  <div>

    <Panel title="站点管理" useBack>
         <ModifyForm
        slot="body"
        :editColumn="editColumn"
        :temporaryData='temporaryData'
        labelWidth="150px"
        :updateData="updateData"
      >
        <p
          slot="title"
        ></p>
        <div style="width:800px;height:400px" slot='mapSite'>
          <base-map-search
            v-if="isSetMap"
            ref="mapSearch"
            :city="cityName"
            :value="address"
            :longitude="lng"
            :latitude="lat"
            :isEdit="isEdit"
            @updateLocation="updateLocation"
          />
        </div>
        <div slot='city'>
            <!-- <el-cascader :props="props" :options="province" v-model='hid'></el-cascader> -->
            <el-select v-model="provinceId" @change="changeCity" placeholder="请选择省">
              <el-option
                v-for="item in province"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="cityId" @change="changeArea" placeholder="请选择市">
              <el-option
                v-for="item in city"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-select v-model="hid" placeholder="请选择区">
              <el-option
                v-for="item in area"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
        </div>

        <div slot="siteImages">
            <FileUpload 
              propName='id'
              @infoData="infoData"
              @removeImage="removeImage"
              :multiple='true'
              :info='fullImage'
              :limit='8'
              :baseUrl='baseUrl'
              :postUrl='postUrl' />
        </div>

      </ModifyForm>
    </Panel>
  </div>
</template>
<script>
import Panel from "@/components/Panel";
import ModifyForm from "@/components/ModifyForm";
import ModalPanel from "@/components/ModalPanel";
import FileUpload from '@/components/FileUpload';
import request from "@/tools/request";
import BaseMapSearch from '@/components/map/SearMap'

export default {
  name: 'sitedetail_',
  components: {
    FileUpload,
    Panel,
    ModalPanel,
    ModifyForm,
    BaseMapSearch
  },
  props: ["visible", "isEdit", "detail"],
  data() {
    return {
      isSetMap: false,
      siteDialog: false,
      primitiveData: {},
      searchKey: "",
      markers: [],
      cityName: '',
      center: [104.06, 30.67],
      zoom: 17,
      lng: 0,
      lat: 0,
      address:'',
      baseUrl:'',
      postUrl:'',
      title:'',
      fullImage:[],
      addrPoint:{
        
      },
      pics: [],
      hid:'',
      provinceId:'',
      cityId:'',
      city:[],
      area:[],
      province:[],
      configValue:"",
      editorOption: {},
      typeList: [],
      position:{},
      
      temporaryData: {
      },
      editColumn: [
        {
          name: "站点名称",
          prop: "name",
          type: "text",
          width:12,
          required: true
        }, 
        {
          name: "场站编码",
          prop: "stationId",
          type: "text",
          width:12,
          required: true
        }, 
       {
          name: "站点类型",
          prop: "type",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择类型"},{'id': 1,'name': "自营"},{'id':2, 'name':"第三方"},{'id':3, 'name':"租用"},{'id':9, 'name':"私人"}],
          width:12,
          required: true
        }, 
        {
          name: "站点枪数量",
          prop: "gunNum",
          type: "number",
          width:12,
          required: true
        },
        {
          name: "站点桩数量",
          prop: "pileNum",
          type: "number",
          width:12,
          required: true
        },
        {
          name: "负责人",
          prop: "contacts",
          type: "text",
          width:12,
          required: true
        },
        {
          name: "负责人电话",
          prop: "contactsPhone",
          type: "number",
          width:12,
          required: true
        },
        {
          name: "服务电话",
          prop: "serviceMobile",
          type: "text",
          width:12,
          required: true
        },
        {
          name: "监管平台ID",
          prop: "superviseId",
          type: "text",
          width:12,
          required: true
        },

        {
          name: "监管平台名字",
          prop: "superviseName",
          type: "text",
          width:12,
          required: false
        },
        {
          name: "站点状态",
          prop: "state",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择状态"},{'id': 1,'name': "启用"},{'id':2, 'name':"未启用"},{'id':3, 'name':"停业"},{'id':4, 'name':"离网"}],
          width:12,
          required: true
        },
        {
          name: "未入场是否允许充电",
          prop: "noAdmissionCanCharge",
          type: "select",
          optionBindLabel: 'name',
          optionBindValue: 'id',
          optionList: [{'id': '','name': "请选择"},{'id': true,'name': "是"},{'id':false, 'name':"否"}],
          width:12,
          required: true
        }, 
        {
          name: "变压器装机容量(KW)",
          prop: "transformerCapacity",
          type: "number",
          width:12,
          required: false
        },
        {
          name: "变压器当前功率(KW)",
          prop: "transformerPower",
          type: "number",
          width:12,
          required: false
        },
        {
          name: "变压器保留容量(KW) ",
          prop: "transformerRetainCapacity",
          type: "number",
          width:12,
          required: false
        },
        {
          name: "通知",
          prop: "desc",
          type: "text",
          width:12,
          required: false
        },
        {
          name: "备注",
          prop: "mark",
          type: "text",
          width:12,
          required: false
        },
        // {
        //   name: "停车备注",
        //   prop: "parkDesc",
        //   type: "text",
        //   width:12,
        //   required: false
        // },
        {
          name: "区域",
          width: 24,
          prop: "hid",
          type: "other",
          slotName: "city",
          required: false
        },
        {
          name: "站点图片",
          width: 24,
          prop: "pics",
          type: "other",
          slotName: "siteImages",
          required: false
        },
        {
          name: "位置描述",
          width: 24,
          prop: "address",
          type: "text",
          // slotName: "mapSite",
          required: false
        },
        {
          name: "经纬度",
          width: 24,
          prop: "address",
          type: "other",
          slotName: "mapSite",
          required: false
        },
        
      ],
    };
  },
  computed: {
  },
  methods: {
   
    initSearch() {
      let vm = this;
      let map = this.amapManager.getMap();
      AMapUI.loadUI(["misc/PoiPicker"], function(PoiPicker) {
        let poiPicker = new PoiPicker({
          input: "search",
          placeSearchOptions: {
            map: map,
            pageSize: 10
          },
          suggestContainer: "searchTip",
          searchResultsContainer: "searchTip"
        });
        vm.poiPicker = poiPicker;
        // 监听poi选中信息
        poiPicker.on("poiPicked", function(poiResult) {
          let source = poiResult.source;
          let poi = poiResult.item;
          if (source !== "search") {
            poiPicker.searchByKeyword(poi.name);
          } else {
            poiPicker.clearSearchResults();
            vm.markers = [];
            let lng = poi.location.lng;
            let lat = poi.location.lat;
            
            let address = poi.name; // poi.cityname + poi.adname + poi.name
            vm.center = [lng, lat];
            vm.markers.push([lng, lat]);
            vm.lng = lng;
            vm.lat = lat;
            vm.address = address;
            vm.searchKey = address;
            vm.$emit("updateLocation", lng, lat, vm.searchKey);
          }
        });
      });
    },
    
    // 地图搜索选址
    updateLocation(lng, lat, address) {
          this.lng = lng;
          this.lat = lat;
          console.log('lng',lng, lat)
          this.address = address;
          // this.$emit('handelAddress', {lng, lat, address})
        },
        handleClose() {
          this.$emit("update:visible", false);
        },
    infoData(data){
      this.pics = [...this.pics, this.$baseUrl+data.file]
      var pics = this.$baseUrl+data.file
      this.fullImage=[...this.fullImage, pics]
    },
    removeImage(index){
      this.pics.splice(index, 1)
    },
    qqMapTransBMap(lng, lat) {
          let x_pi = 3.1415926535897932384626 * 3000.0 / 180.0;
          let x = lng;
          let y = lat;
          let z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
          let theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
          let lngs = z * Math.cos(theta) + 0.0065;
          let lats = z * Math.sin(theta) + 0.006;
        
          return {
              lng: lngs,
              lat: lats 
          } 
    },
    bdMapToTxMap(lng, lat) {
      let x_pi = 3.1415926535897932384626 * 3000.0 / 180.0;
      let x = lng - 0.0065;
      let y = lat - 0.006;
      let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      let lngs = z * Math.cos(theta);
      let lats = z * Math.sin(theta);
      let point = {
        lng: lngs,
        lat: lats        
        }   
      return point
    },
   async updateData(values) {
    //  let point = this.bdMapToTxMap(this.position.lng, this.position.lat)
     let lng = this.lng
     let lat = this.lat
    //  let address = this.address
     let pics = this.pics
     if(!this.hid){ return this.$message.error('请选择区域')}
     let hid = this.hid
     let cityId = this.cityId
     let provinceId = this.provinceId
     const  { address,id, name, type, desc, serviceMobile,superviseId,superviseName, contacts, contactsPhone, state, mark,gunNum, pileNum, transformerRetainCapacity, transformerPower, transformerCapacity, stationId, noAdmissionCanCharge } = values
     let url = id ? "/iot/site/update" : "/iot/site/add"
     let msg = id ? "编辑成功" : "添加成功"
     let res= await request({
       url: url,
       method: "POST",
       data:{pics, id, name, type, desc, serviceMobile,superviseId,superviseName, contacts, contactsPhone, state, lng, lat, cityId, provinceId, mark, address, hid, gunNum, pileNum, transformerRetainCapacity, transformerPower, transformerCapacity, stationId, noAdmissionCanCharge  }
     })
     if(res.code !==0) return
      this.$message.success(msg)
      this.$router.go(-1)
    },
    async fetchTypelist(){
      const result = await GET('/type/getAll', {
        type: 2
      })
      this.editColumn[2].optionList = result
    },
    async fetchData(id){
      let { info } = await request({
        url: "/iot/site/info/"+id,
        method: "GET",
        data: {}
      });
       if(info.pics !=''){
         let tupian = JSON.parse(info.pics)
         this.pics = tupian
         let full = tupian.map(item => {
          // item = 'http://192.168.1.99:8080'+item
          return item
          })
        this.fullImage =  full
       }
      
      //  console.log('--图片',info.address)
      this.temporaryData = info
      this.provinceId = info.provinceId
      this.cityId =  info.cityId
      this.hid = info.hid
      var {lng, lat } = info
      // this.address = info.address
      this.position = {lng, lat }
      this.center = [lng, lat]
      this.lng = lng
      this.lat = lat
      this.isSetMap = true
      this.getCity()
      this.getArea()
      //  if(info){
      //   let that = this
      //   setTimeout(() => {
      //     // that.getCity()
      //     // that.getArea()
      //     // that.setAddress()
      //   }, 200);
      // }
      // document.querySelector(".search-box-wrapper input").value = info.address
     
      // console.log('数据',info)
      
    },
    //渲染区域
    handleChange (value) {
        // console.log('地图',value)
      },

    async getProvince() {
       let res= await request({
       url: '/zoning/search/province',
       method: "GET",
       data:{}
     })
     if(res.code ==0){
       this.province = res.list
     }
    },
    changeCity(){
      this.cityId = ''
      this.hid = ''
      this.getCity()
    },
    changeArea(){
      this.hid = ''
      this.getArea()
    },
    async getCity() {
       let res= await request({
       url: '/zoning/search/city',
       method: "POST",
       data:{provinceId:this.provinceId}
     })
     if(res.code ==0){
       this.city = res.list
     }
    },
    async getArea() {
       let res= await request({
       url: '/zoning/search/county',
       method: "POST",
       data: {cityId:this.cityId}
     })
     if(res.code ==0){
       this.area = res.list
     }
    },
  },
  created() {
   
  },
  mounted() {
    this.getProvince()
    this.baseUrl = this.$baseUrl
    this.postUrl = this.$baseUrl + '/file/banner'
    if(this.$route.query.id){
      this.fetchData(this.$route.query.id)
    

    }else{
      this.address = '成都市'
      this.isSetMap = true
    }
    

    
  }
};
</script>

<style lang='scss' >
.contain{
    width: 100%;
    height: 600px;
    position: relative;
  }
.el-input--medium .el-input__inner {
		min-width: 180px;
		max-width: 220px !important;
	}
.amap-wrapper {
  width: 800px;
  height: 360px;
}
.autoAddressClass{
  li {
    i.el-icon-search {margin-top:11px;}
    .mgr10 {margin-right: 10px;}
    .title {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .address {
      line-height: 1;
      font-size: 12px;
      color: #b4b4b4;
      margin-bottom: 5px;
    }
  }
}
</style>